package com.linkivr.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.linkivr.dao.*;
import com.linkivr.model.*;
import com.linkivr.util.GL;

@Component("userDao")
public class UserDaoImpl implements UserDao {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void add(T_user tabObj) {
		
		sessionFactory.getCurrentSession().merge(tabObj);
	}

	public int delete(int id) {
		
		return sessionFactory.getCurrentSession().createQuery("delete T_user  where user_id=:id ").setInteger("id", id)
				.executeUpdate();
	}

	public void update(T_user tabObj) {
		sessionFactory.getCurrentSession().merge(tabObj);
	}

	@SuppressWarnings("unchecked")
	public List<T_user> queryAll() {
		
		String hql = "from T_user ";
		GL.info(hql);
		return sessionFactory.getCurrentSession().createQuery(hql).list();
	}

	@SuppressWarnings("unchecked")
	public List<T_user> queryAll(int start, int limit) {
		String hql = "from T_user  order by user_id desc ";
		GL.info(hql);
		return sessionFactory.getCurrentSession().createQuery(hql).setFirstResult(start).setMaxResults(limit).list();
	}

	public T_user query(int id) {
		String hql = "from T_user where  user_id=:id";
		GL.info(hql);
		return (T_user) sessionFactory.getCurrentSession().createQuery(hql).setInteger("id", id).uniqueResult();

	}

	public int queryCount() {
		Integer count = 0;
		Long lo = (Long) sessionFactory.getCurrentSession().createQuery("select count(*) from T_user ").uniqueResult();
		count = new Integer(String.valueOf(lo));
		GL.info("queryCount" + count);
		return count;
	}

	@SuppressWarnings("unchecked")
	public boolean checkAccount(String name, String pwd) {
		String hql = "from T_user   where user_name=:name and user_passwd=:pwd";
		GL.info(hql);
		List<T_user> managers = sessionFactory.getCurrentSession().createQuery(hql).setString("name", name)
				.setString("pwd", pwd).list();
		if (managers != null && managers.size() > 0) {
			return true;
		}
		return false;
	}
}
